var MAX_PERCENT = 100;
var currTarget = null;
var editIndex = undefined;
var currPercArr=[];
var templeteArr = [];

$(function(){
    $.ajax({
        url: '/timemodel/templeteList',
        type: 'GET',
        dataType: 'json',
        contentType: "application/json",
        success: function(data){
            templeteArr = data;
        },
        error:function(data){   
             console.log(data);
        }
    });  

    $('#tt').edatagrid({
       // updateUrl: '/channelLimitModel/batchUpdate',
       // url: modelListUrl,
       autoSave: false,
       batchSave: true,
       onBeforeSave:function(index){
           var _self = this;
           var len= $(this).datagrid('getData').rows.length;
           var rows = $(this).datagrid('getRows');
           var totalCurrPerc = 0;
           var remainPerc = 0;
           var currPerc = retentHandler.transformToDx2(parseFloat($("td[field='currPercent'] input").val()));
           for(var i = 0; i< len; i++){
                if(index == i){
                    continue;
                }
                remainPerc = retentHandler.transformToDx2(remainPerc + rows[i].currPercent);
            }
            totalCurrPerc = retentHandler.transformToDx2(remainPerc + currPerc);
            if(totalCurrPerc >  MAX_PERCENT) {
                $.messager.alert('提示:','占比超过了100%，请重新调整！', null,  function(){
                    $(_self).edatagrid('editRow', index);
                    $("td[field='currPercent'] input").focus();
                });
                return false;
            }   
            showProcess(true, '正在更新中...', '正在计算中...');   
            retentHandler.updateChart(index, currPerc, totalCurrPerc, currPercArr);
            retentHandler.updateTable(rows, index, currPerc, currPercArr);
            showProcess(false);
        },
        onAfterEdit: function(index, row){
            // console.log('onAfterEdit:'+ index);
        }
       
    });

    $.extend($.fn.edatagrid.methods, {
        editRow: function(jq, index){
            return jq.each(function(){
                var dg = $(this);
                var rows = dg.datagrid('getRows');
                var row = rows[index];
                /*var status = row && row['status'];*/
                var opts = $.data(this, 'edatagrid').options;
                var editIndex = opts.editIndex;
                if (editIndex != index){
                    if (dg.datagrid('validateRow', editIndex)){
                        dg.datagrid('beginEdit', index);
                        opts.editIndex = index;
                        // opts.onEdit.call(this, index, row);  
                    } else {
                        setTimeout(function(){
                            dg.datagrid('selectRow', editIndex);
                        }, 0);
                    }
                }
            });
        }
    });

    $(document).on('blur', '.datagrid-view td[field=currPercent] input', function(){
        $('#tt').edatagrid('saveRow');
    });
});  

function doSearch(){
    var mark = $('#mark').combobox('getValue');  
    $('#templeteName').combobox("clear");
    currPercArr = [];
    /*$('#tt').datagrid('load', {    
    	mark: mark,
    	channelName: $('#channelName').val(),
    	apkName: $('#apkName').val()
    });*/ 
    
    if(mark !=''){
        $.ajax({
            url: modelListUrl,
            data:{'mark':mark},
            async:true,
            success:function(data){
                doSearchNoReq(data.rows);
                $('#tt').datagrid('loadData', data);
            }
        });
    }else{
    	$("#container").css({'display':'none'});
    }
}

function doSearchNoReq(data){
    currPercArr = [];
    $("#container").css({'display':'block'});
    var timeData=[];
    retentHandler.getTimeX();
    if(data.length!=0){
        $("#container").css({'width':'100%','height':'600px','margin':'0 auto'});
    }else{
        $("#container").css({'display':'none'});
    }
    $.each(data,function(index,mod){
        currPercArr.push(mod.currPercent);
    });
    retentHandler.showHighChart(currPercArr);
}

function updateTableOld(rows, index, currPerc, currPercArr){
    var len = rows.length;
    rows[index].currPercent = retentHandler.transformToDx2(currPerc);
    for(var i = 0; i< len; i++){
        if(index == 0){
            if(i == index){
                rows[i].timePercent = retentHandler.transformToDx2(currPerc);
            }else{
                rows[i].timePercent = retentHandler.transformToDx2(rows[i-1].timePercent + rows[i].currPercent);
            }
            
        }else{
            if(i < index){
                continue;
            }else if(i == index){
                rows[i].timePercent = retentHandler.transformToDx2(rows[i-1].timePercent + currPerc);
            }else if(i > index){
                rows[i].timePercent = retentHandler.transformToDx2(rows[i-1].timePercent + rows[i].currPercent);
            }
        }
        $('#tt').datagrid('updateRow',{
            index: i,
            row: rows[i]
        }); 
    } 
}

function add(){
    showMyWindow('模拟配置管理 |模拟新增配置管理', '/channelapk/addConfig', 800, 500);
}
function edit(){
	var row = $('#tt').datagrid('getSelected');
	var mark = row.mark;
    if (row){
	    showMyWindow('模拟器配置管理 | 编辑模拟器配置', '/channelapk/'+mark+'/configUpdate', 700, 500);
    } else {
    	showMsg(market.content.title, market.content.tips, alert);
    }
}
function saveRow(url){
    var rows = $('#tt').datagrid('getRows');
    if((rows[95].timePercent < 100 || rows[95].timePercent > 100)) {
        $.messager.alert('提示:','请确保总的占比为100%！');
        return;
    }
    showConfirm(market.content.title, "确定要保存么", function(){
        $.ajax({
            url: url,
            type: 'POST',
            data: JSON.stringify(rows),
            dataType: 'json',
            contentType: "application/json",
            success: function(data){
                $.messager.alert('提示:','保存成功！');
                // doSearch();
            },
            error:function(data){   
                 $.messager.alert('提示:','保存失败！');
                 console.log(data);
            }
        });
   });
}

function formatterModel(value,row,index){
	 var a = '<a href="#" onclick="editModel('+"'"+row.mark+"'"+')">配置</a> ';
	 return a;
}


function formatterValue(value,row,index){
	 return value.toFixed(2);;
}

function onSelectMark(){
    var mark = $('#mark').combobox('getValue');  
    if(mark !=''){
        $('#templeteName').combobox('loadData', templeteArr).combobox('clear'); 
    }

}

function onSelectTemplete(){
    var templeteName = $('#templeteName').combobox('getValue');  
    $.ajax({
        url: '/timemodel/timemodelList?parentId=' + templeteName,
        type: 'GET',
        dataType: 'json',
        contentType: "application/json",
        success: function(data){
            var len = data.length;
            var mark = $('#mark').combobox('getValue'); 
            for(var i = 0; i < len; i++){
                data[i].mark = mark;
            }
            $('#tt').datagrid('loadData', data);
            doSearchNoReq(data);
        },
        error:function(data){   
             $('#message').text('系统错误');
             $('#alertForm').modal('show');
             console.log(data);
        }
    });    
    
}

//占比输入框限制，最大为100且只最多能有两位小数点 

$(document).on("keyup afterpaste","td[field='timePercent'] input",function(e){
		 this.value = this.value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符   
		 this.value = this.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的   
		 this.value = this.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");  
		 this.value = this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数   
		 if(this.value.indexOf(".")< 0 && this.value !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额  
			 this.value= parseFloat(this.value);  
		 }  
		 if(this.value>100){
			 this.value = 100;
		 }
})
//日限输入框限制为数字
$(document).on("keyup afterpaste","td[field='spDayLimit'] input",function(){
	$("td[field='spDayLimit'] input").attr("maxlength",'9');
	this.value=this.value.replace(/\D/g,'');
})
